package com.ljf.servlet.repeatable;


import com.ljf.framework.util.LjfStringUtil;
import com.ljf.framework.util.json.LjfJsonUtilManager;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 构建可重复读取inputStream的request
 */
public class RepeatedlyRequestWrapper extends HttpServletRequestWrapper {
    private final byte[] body;

    public RepeatedlyRequestWrapper(HttpServletRequest request, ServletResponse response) throws IOException {
        super(request);
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        body = HttpHelper.getBodyString(request).getBytes("UTF-8");
        Map paramBodyMap = new HashMap();
        if (!LjfStringUtil.isEmpty(body.toString())) {
            paramBodyMap = LjfJsonUtilManager.parseJsonToMap(new String(body));

        }
        paramBodyMap.forEach((k,v) -> {
            request.setAttribute((String) k,v);
        });

    }
//    gateway 使用
//    public RepeatedlyRequestWrapper(HttpServletRequest request, ServletResponse response, GatewayLog gatewayLog) throws UnsupportedEncodingException {
//        super(request);
//        request.setCharacterEncoding("UTF-8");
//        response.setCharacterEncoding("UTF-8");
//        String bodyString = HttpHelper.getBodyString(request);
//        gatewayLog.setRequestBody(bodyString);
//        body = bodyString.getBytes("UTF-8");
//    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public int read() throws IOException {
                return bais.read();
            }

            @Override
            public int available() throws IOException {
                return body.length;
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }



}
